/*
 * Mapa zarządzająca mapą. Wczytuje mapę z pliku, wykrywa kolizje.
 */
#include "MapManager.h"

MapManager *MapManager::instance = NULL;
MapManager::MapManager()
{
	FILE *fp = fopen("res/maps/default.map", "r");
	fscanf(fp, "%d x %d\n", &hTNum, &vTNum);
	ATile *t;
	
	BITMAP *tankOneBmp = load_bitmap("res/img/standard/tank.bmp", NULL);
	tankOne = new Tank(tankOneBmp);
	
	BITMAP *tankTwoBmp = load_bitmap("res/img/standard/tank.bmp", NULL);
	tankTwo = new Tank(tankTwoBmp);
	
	bool tankInited = false;
	
	for ( int j = 0; j < hTNum; j++)
	{
		for (int i = 0; i < vTNum; i++)
		{
			char c = getc(fp);
			if(c == 'W')
			{
				t = new Wall(load_bitmap("res/img/standard/wall.bmp", NULL));
				t->x = i*width;
				t->y = j*height;
				map[i][j] = t;
				DisplayManager::getInstance()->add(t);
			}
			else if(c == 'T')
			{
				map[i][j] = NULL;
				if(tankInited == false)
				{
					tankInited = true;
					tankOne->x = i*width;
					tankOne->y = j*height;
				} else
				{
					tankTwo->x = i*width;
					tankTwo->y = j*height;
				}
			}
			else
			{
				map[i][j] = NULL;	
			}
		}
		if( getc(fp) != '\n' ) ; //printf("ERROR!");
	}	
}

MapManager *MapManager::getInstance()
{
	if (instance == NULL)
	{
		instance = new MapManager();
	}

	return instance;
}

bool MapManager::intersects ( int b1_x, int b1_y, int b1_w, int b1_h, int b2_x, int b2_y, int b2_w, int b2_h )
{
	if ( ( b1_x > b2_x + b2_w - 1 )  ||  
	( b1_y > b2_y + b2_h - 1 )       ||  
	( b2_x > b1_x + b1_w - 1 )       ||  
	( b2_y > b1_y + b1_h - 1 ) )         
	{
			return false;
	}
	return true;
}
ATile *MapManager::getTile(int i, int j)
{
	if(i >= 0 && i < vTNum && j >= 0 && j < hTNum)
		return map[i][j];
	else 
		return NULL;
}

bool MapManager::ifWallIntersects(ATile &tank, int i, int j)
{
	ATile *tile = getTile(i, j);
	if(tile == NULL)
		return false;
	
	return intersects(tile->x, tile->y, tile->getImage()->w, tile->getImage()->h,
						tank.x, tank.y, tank.getImage()->w, tank.getImage()->h); // x, y, w, h, x1, y1, w1, h1
}
bool MapManager::tankIntersects(Tank &tank)
{
	int i = getI(tank.x);
	int j = getJ(tank.y);
	if(		   ifWallIntersects(tank, i, j)
			|| ifWallIntersects(tank, i-1, j)
			|| ifWallIntersects(tank, i+1, j)
			|| ifWallIntersects(tank, i, j+1)
			|| ifWallIntersects(tank, i-1, j+1)
			|| ifWallIntersects(tank, i+1, j+1)
			|| ifWallIntersects(tank, i, j-1)
			|| ifWallIntersects(tank, i-1, j-1)
			|| ifWallIntersects(tank, i+1, j-1)
		)
	{
		return true;
	}
	return false;
}
int MapManager::getI(int x)
{
	return (int) x/width;
}
int MapManager::getJ(int y)
{
	return (int) y/height;
}

MapManager::~MapManager()
{
}
